package cn.sumpu.toolkit.weibo;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import weibo4j.User;
import weibo4j.Weibo;
import weibo4j.WeiboException;
import weibo4j.http.AccessToken;
import weibo4j.http.ImageItem;
import weibo4j.http.RequestToken;

public class SinaWeibo {
	/**
	 * 代表  Request Token which is passed to the service provider when acquiring the authorized Access Token
	 */
	private static RequestToken requestToken = null;
	private String appKey;
	private String appSecret;
	
	/**
	 * 
	 * @param appKey 新浪微博审核通过的appkey
	 * @param appSecret 新浪微博审核通过的appSecret
	 */
	public SinaWeibo(String appKey,String appSecret){
		this.appKey=appKey;
		this.appSecret=appSecret;
	}
	
	/**
	 * 发起授权请求，带回掉地址
	 * @param callbackUrl回调地址
	 * @return 请求的地址
	 */
	public  String requestOauth(String callbackUrl) {
		try {
			Weibo weibo = new Weibo();
			weibo.setOAuthConsumer(appKey, appSecret);
			requestToken = weibo.getOAuthRequestToken(callbackUrl);
			return requestToken.getAuthorizationURL();
		} catch (WeiboException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 发起授权请求
	 * @return 请求的地址
	 */
	public  String requestOauth() {
		try {
			Weibo weibo = new Weibo();
			weibo.setOAuthConsumer(appKey, appSecret);
			requestToken = weibo.getOAuthRequestToken();
			return requestToken.getAuthorizationURL();
		} catch (WeiboException e) {
			e.printStackTrace();
			return null;

		}
	}

	/**
	 * 获取用户授权信息
	 * 
	 * @param oauthVerifier
	 *            授权码
	 * @return AccessToken
	 */
	public  AccessUser requstAccessToken(String oauthVerifier) {
		try {
			AccessToken accessToken = null;
			accessToken = requestToken.getAccessToken(oauthVerifier);
			Long luid = accessToken.getUserId();
			Weibo weibo = new Weibo();
			weibo.setOAuthConsumer(appKey,appSecret);
			weibo.setToken(accessToken.getToken(), accessToken.getTokenSecret());
			User user = weibo.showUser(luid.toString());
			AccessUser accessUser=new AccessUser();
			accessUser.setUid(luid.toString());
			accessUser.setName(user.getScreenName());
			accessUser.setHeadUrl(user.getProfileImageURL().toString());
			accessUser.setAccessToken(accessToken.getToken());
			accessUser.setAccessSecret(accessToken.getTokenSecret());
			accessUser.setDesc("sinaWeibo");
			return accessUser;
		} catch (WeiboException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 根据用户ID获取用户资料（授权用户）
	 * 
	 * @param accessToken 用户授权认证信息
	 * @param accessSecret 用户授权认证信息
	 */
	public  AccessUser getUserInfo(String userId, String accessToken,
			String accessSecret) {
		try {
			Weibo weibo = getWeiboOauth(accessToken, accessSecret);
			User user = weibo.showUser(userId);
			AccessUser accessUser=new AccessUser();
			accessUser.setUid(userId);
			accessUser.setName(user.getScreenName());
			accessUser.setHeadUrl(user.getProfileImageURL().toString());
			return accessUser;
		} catch (WeiboException e) {
			e.printStackTrace();
			return null;
		}

	}

	// 设置授权以便调取相应接口
	private  Weibo getWeiboOauth(String accessToken, String accessSecret) {
		Weibo weibo = new Weibo();
		weibo.setOAuthConsumer(appKey, appSecret);
		weibo.setToken(accessToken, accessSecret);
		return weibo;
	}

	/**
	 * 分享内容到新浪微博
	 * @param text 文本内容
	 * @param url 分享的链接
	 * @param picUrl 图片链接
	 * @param site 网站来源
	 * @param appkey 授权的认证
	 */
	public String share(String text,String url,String picUrl,String site,String appkey){
		
		return "http://service.weibo.com/share/share.php?site="+site+"&title="+text+"&url="+url+"&pic="+picUrl+"&appkey="+appkey;
	}
	
	/**
	 * 分享内容到新浪微博
	 * @param text 文本内容
	 * @param url 分享的链接
	 * @param site 网站来源
	 * @param appkey 授权的认证
	 */
	public String shareUrl(String text,String url,String site,String appkey){
		
		return "http://service.weibo.com/share/share.php?site="+site+"&title="+text+"&url="+url+"&appkey="+appkey;
	}
	
	/**
	 * 分享内容到新浪微博
	 * @param text 文本内容
	 * @param picUrl 图片链接
	 * @param site 网站来源
	 * @param appkey 授权的认证
	 */
	public String sharePic(String text,String picUrl,String site,String appkey){
		
		return "http://service.weibo.com/share/share.php?site="+site+"&title="+text+"&pic="+picUrl+"&appkey="+appkey;
	}
	
	/**
	 * 分享内容到新浪微博
	 * @param text 文本内容
	 * @param site 网站来源
	 * @param appkey 授权的认证
	 */
	public String shareText(String text,String site,String appkey){
		
		return "http://service.weibo.com/share/share.php?site="+site+"&title="+text+"&appkey="+appkey;
	}
	
	/**
	 * 发布一条微博信息(文本内容)
	 * 
	 * @param accessToken
	 *            授权认证信息
	 * @param accessSecret
	 *            授权认证信息
	 * @param text
	 *            发送的文本内容
	 */
	public  void sendMessage(String text, String accessToken,
			String accessSecret) {
		try {
			Weibo weibo = getWeiboOauth(accessToken, accessSecret);
			weibo.updateStatus(text);
		} catch (WeiboException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 上传图片并发布一条微博
	 * 
	 * @param accessToken
	 *            授权认证信息
	 * @param accessSecret
	 *            授权认证信息
	 * @param text
	 *            发送的文本内容
	 * @param picUrl
	 *            网络图片路径
	 */
	public  void sendMessageNetPic(String text, String picUrl,
			String accessToken, String accessSecret) {
		try {
			Weibo weibo = getWeiboOauth(accessToken, accessSecret);
			byte[] content = picUrlToByte(picUrl);
			ImageItem pic = new ImageItem("pic", content);
			weibo.uploadStatus(text, pic);
		} catch (WeiboException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 上传图片并发布一条微博
	 * 
	 * @param accessToken
	 *            授权认证信息
	 * @param accessSecret
	 *            授权认证信息
	 * @param text
	 *            发送的文本内容
	 * @param picUrl
	 *            本地图片路径
	 */
	public  void sendMessageLocalPic(String text, String picUrl,
			String accessToken, String accessSecret) {
		try {
			Weibo weibo = getWeiboOauth(accessToken, accessSecret);
			File file = new File(picUrl);
			weibo.uploadStatus(text, file);
		} catch (WeiboException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 微博关注
	 * 
	 * @param accessToken
	 *            授权认证信息
	 * @param accessSecret
	 *            授权认证信息
	 * @param weiboUserId
	 *            关注的微博帐号id
	 */
	public  void addFollow(String weiboUserId, String accessToken,String accessSecret) {
		try {
			Weibo weibo = getWeiboOauth(accessToken, accessSecret);
			weibo.createFriendshipByUserid(weiboUserId);
		} catch (WeiboException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 取消微博关注
	 * 
	 * @param accessToken
	 *            授权认证信息
	 * @param accessSecret
	 *            授权认证信息
	 * @param weiboUserId
	 *            取消关注的微博帐号id
	 */
	public  void delFollow(String weiboUserId, String accessToken,
			String accessSecret) {
		try {
			Weibo weibo = getWeiboOauth(accessToken, accessSecret);
			weibo.destroyFriendship(weiboUserId);
		} catch (WeiboException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 判断是否关注
	 * 
	 * @param accessToken
	 *            授权认证信息
	 * @param accessSecret
	 *            授权认证信息
	 * @param weiboUserId
	 *            取消关注的微博帐号id
	 * @return true 存在关注关系 false 不存在关注关系
	 */
	public  Boolean isFriend(String userA, String userB,
			String accessToken, String accessSecret) {
		try {
			Weibo weibo = getWeiboOauth(accessToken, accessSecret);
			Boolean isFriend = weibo.existsFriendship(userA, userB);
			return isFriend;
		} catch (WeiboException e) {
			e.printStackTrace();
			return false;
		}

	}

	/**
	 * 网络图转化为字节数组
	 * @param picUrl 网络图片地址
	 * @return byte[] 字节数组
	 */
	public  byte[] picUrlToByte(String picUrl) {
		URL urlObj;
		byte[] b = null;
		try {
			urlObj = new URL(picUrl);
			URLConnection connection = urlObj.openConnection();
			InputStream is = connection.getInputStream();
			b = inputStreamToByte(is);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return b;
	}

	private  byte[] inputStreamToByte(InputStream is) throws IOException {
		ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
		int ch;
		while ((ch = is.read()) != -1) {
			bytestream.write(ch);
		}
		byte imgdata[] = bytestream.toByteArray();
		bytestream.close();
		return imgdata;
	}

}
